﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Vehicle : MonoBehaviour {
    public SteerBase[] m_Steers;
    public float m_fMaxSpeed = 10;
    public float m_fMaxForce = 100;
    public float m_fMass = 1;
    //速度
    public Vector3 m_v3Velocity;
    //合力
    public Vector3 m_v3Forces;
    //加速度
    public Vector3 m_v3Acceleration;
    private GroupRadar m_pRadar;
    //摩擦力,当没有力作用在身上的时候去归零速度
    public float m_fDamping = 1;
    //转向的角速度
    public float m_fRotation = 1;
    public float m_fIgnoreRotation = 0.2f;

    public List<GameObject> Neighbors
    {
        get
        {
            if (m_pRadar == null)
                return null;
            else
                return m_pRadar.GetNeighbors();
        }
    }

    public Vector3 Postion
    {
        get { return transform.position; }
    }

    public Vector3 Forward
    {
        get { return transform.forward; }
    }

    public void GetSteers()
    {
        m_Steers = GetComponents<SteerBase>();
        for (int i = 0; i < m_Steers.Length; i++)
        {
            m_Steers[i].Init(this);
        }
        m_pRadar = GetComponent<GroupRadar>();
    }

    public void CalculateForces()
    {
        m_v3Forces = Vector3.zero;
        for (int i = 0; i < m_Steers.Length; i++)
        {
            if (m_Steers[i].enabled)
            {
                m_v3Forces += m_Steers[i].Force * m_Steers[i].Weight;
            }
        }
        m_v3Forces = Vector3.ClampMagnitude(m_v3Forces, m_fMaxForce);
        m_v3Acceleration = m_v3Forces / m_fMass;
    }

    public void UpdatePos(float deltaTime)
    {
        m_v3Velocity = m_v3Velocity + m_v3Acceleration * deltaTime;
        m_v3Velocity = Vector3.ClampMagnitude(m_v3Velocity, m_fMaxSpeed);
        if (m_v3Forces.Equals(Vector3.zero))
        {
            m_v3Velocity = Vector3.zero;
        }
        //位移
        transform.position += m_v3Velocity * deltaTime;
        //转向
        if (m_v3Velocity.magnitude > m_fIgnoreRotation)
        {
            transform.forward = Vector3.Slerp(transform.forward, m_v3Velocity, m_fRotation * deltaTime);
        }
    }

    public void FreshRadar()
    {
        if(m_pRadar != null)
        {
            m_pRadar.FreshNeighbors();
        }
    }
}
